package com.YHVision.qiuzhike.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.YHVision.qiuzhike.annotation.AuthCheck;
import com.YHVision.qiuzhike.common.BaseResponse;
import com.YHVision.qiuzhike.common.DeleteRequest;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.common.ResultUtils;
import com.YHVision.qiuzhike.constant.UserConstant;
import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.model.dto.postBank.PostBankAddRequest;
import com.YHVision.qiuzhike.model.dto.postBank.PostBankEditRequest;
import com.YHVision.qiuzhike.model.dto.postBank.PostBankQueryRequest;
import com.YHVision.qiuzhike.model.dto.postBank.PostBankUpdateRequest;
import com.YHVision.qiuzhike.model.entity.PostBank;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.PostBankVO;
import com.YHVision.qiuzhike.service.PostBankService;
import com.YHVision.qiuzhike.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 职位库接口
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@RestController
@RequestMapping("/postBank")
@Slf4j
public class PostBankController {

    @Resource
    private PostBankService postBankService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建职位库
     *
     * @param postBankAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addPostBank(@RequestBody PostBankAddRequest postBankAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(postBankAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        PostBank postBank = new PostBank();
        BeanUtils.copyProperties(postBankAddRequest, postBank);
        // 数据校验
        postBankService.validPostBank(postBank, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        postBank.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = postBankService.save(postBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newPostBankId = postBank.getId();
        return ResultUtils.success(newPostBankId);
    }

    /**
     * 删除职位库
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deletePostBank(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        PostBank oldPostBank = postBankService.getById(id);
        ThrowUtils.throwIf(oldPostBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPostBank.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = postBankService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新职位库（仅管理员可用）
     *
     * @param postBankUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePostBank(@RequestBody PostBankUpdateRequest postBankUpdateRequest) {
        if (postBankUpdateRequest == null || postBankUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        PostBank postBank = new PostBank();
        BeanUtils.copyProperties(postBankUpdateRequest, postBank);
        // 数据校验
        postBankService.validPostBank(postBank, false);
        // 判断是否存在
        long id = postBankUpdateRequest.getId();
        PostBank oldPostBank = postBankService.getById(id);
        ThrowUtils.throwIf(oldPostBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = postBankService.updateById(postBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取职位库（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PostBankVO> getPostBankVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        PostBank postBank = postBankService.getById(id);
        ThrowUtils.throwIf(postBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(postBankService.getPostBankVO(postBank, request));
    }

    /**
     * 分页获取职位库列表（仅管理员可用）
     *
     * @param postBankQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<PostBank>> listPostBankByPage(@RequestBody PostBankQueryRequest postBankQueryRequest) {
        long current = postBankQueryRequest.getCurrent();
        long size = postBankQueryRequest.getPageSize();
        // 查询数据库
        Page<PostBank> postBankPage = postBankService.page(new Page<>(current, size),
                postBankService.getQueryWrapper(postBankQueryRequest));
        return ResultUtils.success(postBankPage);
    }

    /**
     * 分页获取职位库列表（封装类）
     *
     * @param postBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostBankVO>> listPostBankVOByPage(@RequestBody PostBankQueryRequest postBankQueryRequest,
                                                               HttpServletRequest request) {
        long current = postBankQueryRequest.getCurrent();
        long size = postBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PostBank> postBankPage = postBankService.page(new Page<>(current, size),
                postBankService.getQueryWrapper(postBankQueryRequest));
        // 获取封装类
        return ResultUtils.success(postBankService.getPostBankVOPage(postBankPage, request));
    }

    /**
     * 分页获取当前登录用户创建的职位库列表
     *
     * @param postBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostBankVO>> listMyPostBankVOByPage(@RequestBody PostBankQueryRequest postBankQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(postBankQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        postBankQueryRequest.setUserId(loginUser.getId());
        long current = postBankQueryRequest.getCurrent();
        long size = postBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PostBank> postBankPage = postBankService.page(new Page<>(current, size),
                postBankService.getQueryWrapper(postBankQueryRequest));
        // 获取封装类
        return ResultUtils.success(postBankService.getPostBankVOPage(postBankPage, request));
    }

    /**
     * 编辑职位库（给用户使用）
     *
     * @param postBankEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editPostBank(@RequestBody PostBankEditRequest postBankEditRequest, HttpServletRequest request) {
        if (postBankEditRequest == null || postBankEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        PostBank postBank = new PostBank();
        BeanUtils.copyProperties(postBankEditRequest, postBank);
        // 数据校验
        postBankService.validPostBank(postBank, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = postBankEditRequest.getId();
        PostBank oldPostBank = postBankService.getById(id);
        ThrowUtils.throwIf(oldPostBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPostBank.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = postBankService.updateById(postBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
